package com.ly.jvm;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicStampedReference;

public class ABADemo {

    public static void main(String[] args) {
//        questionABA();
//        ABA解决
        AtomicStampedReference<Integer> atomicStampedReference = new AtomicStampedReference<>(1,1);

        new Thread( () -> {
            int stamp = atomicStampedReference.getStamp();
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            atomicStampedReference.compareAndSet(1,2,stamp,stamp+1);

            atomicStampedReference.compareAndSet(2,1,atomicStampedReference.getStamp(),atomicStampedReference.getStamp()+1);

        },"A").start();

        new Thread( () -> {
            int stamp = atomicStampedReference.getStamp();
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            atomicStampedReference.compareAndSet(1,5,stamp,stamp+1);
            System.out.println(atomicStampedReference.getStamp()+" "+atomicStampedReference.getReference());
        },"B").start();
    }

    public static void questionABA() {
        //ABA问题
        AtomicInteger atomicInteger = new AtomicInteger(1);

        new Thread( () -> {
            atomicInteger.compareAndSet(1,2);
            atomicInteger.compareAndSet(2,1);
        },"A").start();

        new Thread( ()  -> {
            try {
                TimeUnit.SECONDS.sleep(3);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            atomicInteger.compareAndSet(1,11);
            System.out.println(atomicInteger.get());
        }).start();
    }
}
